package clipboard

import (
	"bytes"
	"clipPaste/internal/storage"
	"encoding/base64"
	"image"
	"image/png"
	"strings"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
)

type ImageHandler struct {
	manager *Manager
}

func NewImageHandler(manager *Manager) *ImageHandler {
	return &ImageHandler{
		manager: manager,
	}
}

func (h *ImageHandler) HandleImage(clipboard fyne.Clipboard) error {
	// 获取剪贴板内容
	content := clipboard.Content()
	if content == "" {
		return nil
	}

	// 检查是否为图片格式的 base64 字符串
	if isBase64Image(content) {
		clip := &storage.ClipItem{
			Type:      storage.TypeImage,
			Content:   content,
			Timestamp: time.Now(),
			Preview:   "[Image]",
			Size:      int64(len(content)),
			Hash:      h.manager.hashContent(content),
		}
		return h.manager.store.SaveClip(clip)
	}

	return nil
}

func (h *ImageHandler) RestoreImage(content string) (image.Image, error) {
	// 从 base64 字符串恢复图片
	imgData, err := base64.StdEncoding.DecodeString(content)
	if err != nil {
		return nil, err
	}

	img, err := png.Decode(bytes.NewReader(imgData))
	if err != nil {
		return nil, err
	}

	return img, nil
}

// 检查字符串是否为 base64 编码的图片
func isBase64Image(data string) bool {
	if len(data) < 23 { // 最小的 base64 图片也应该超过这个长度
		return false
	}

	// 检查是否以常见的图片 base64 头部开始
	prefixes := []string{
		"data:image/png;base64,",
		"data:image/jpeg;base64,",
		"data:image/jpg;base64,",
		"data:image/gif;base64,",
	}

	for _, prefix := range prefixes {
		if strings.HasPrefix(data, prefix) {
			return true
		}
	}

	return false
}

// 创建图片预览
func (h *ImageHandler) CreatePreview(content string) (*canvas.Image, error) {
	img, err := h.RestoreImage(content)
	if err != nil {
		return nil, err
	}

	preview := canvas.NewImageFromImage(img)
	preview.FillMode = canvas.ImageFillContain
	preview.SetMinSize(fyne.NewSize(100, 100))

	return preview, nil
}

// 将图片转换为 base64 字符串
func (h *ImageHandler) ImageToBase64(img image.Image) (string, error) {
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		return "", err
	}

	return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}
